package algorithm.leetCode.other;

/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode(int x) { val = x; } }
 */
class Solution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		boolean ifGo = false;
		ListNode head = l1;
		while (l1 != null) {
			l1.val += l2 != null ? l2.val : 0;
			ifGo = l1.val >= 10;
			if (ifGo) {
				if (l1.next == null)
					l1.next = new ListNode(0);
				l1.next.val += 1;
			}
			l1.val %= 10;
			if (l2 != null)
				if (l1.next == null && l2.next != null)
					l1.next = new ListNode(0);
			l1 = l1.next;
			l2 = l2 != null ? l2.next : null;
		}
		return head;
	}
}

public class ListNode2 {
	public static int length(ListNode node) {
		int x = 0;
		while (node != null) {
			node = node.next;
			x++;
		}
		return x;
	}

	public static int[] LinkToArr(ListNode node) {
		int n = length(node);
		int[] x = new int[n];
		for (int i = 0; i < n; i++) {
			x[i] = node.val;
			node = node.next;
		}
		return x;
	}

	public static ListNode ArrToLink(int[] arr) {
		ListNode head = new ListNode(arr[0]);
		ListNode link = head;
		for (int i = 1; i < arr.length; i++) {
			head.next = new ListNode(arr[i]);
			head = head.next;
		}
		return link;
	}

	public static void printArr(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++)
			System.out.print(arr[i] + ",\t");
		System.out.println(arr[arr.length - 1] + "\n");
	}

	public static void main(String[] args) {
		int[] a = new int[] { 0 };
		printArr(a);
		int[] b = new int[] { 7, 3 };
		printArr(b);
		int[] c = LinkToArr(new Solution().addTwoNumbers(ArrToLink(a), ArrToLink(b)));
		printArr(c);

	}
}
